import os
import urllib

from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from utilities import *
from entities import * 

class AddSource(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/AddSource')
        template_values = {
            'header': SiteMaster.Header(self,"topnav_addSource"),
            'footer': SiteMaster.Footer(),
            'css'   : SiteMaster.CSS(),
            'url'   : upload_url,
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/Admin.html')
        self.response.out.write(template.render(path, template_values))

class UploadHandler1(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
    
        version = self.request.get('Version')
        upload_files = self.get_uploads('file')
        appSource = upload_files[0]
        status = Source.Add(appSource,version)
        self.redirect("/")
        
class ServeHandlerApp(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, app_id):
        apps = Entities.Source.get_by_id(int(app_id))
        blob_key = str(apps.StoreSource.key())
        blob_key = str(urllib.unquote(blob_key))
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blobstore.BlobInfo.get(blob_key),save_as=True)
        